package com.baseframe.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baseframe.common.annotation.VisitLog;
import com.baseframe.common.utils.HttpContextUtils;
import com.baseframe.common.utils.IPUtils;
import com.baseframe.sys.controller.AbstractController;
import com.baseframe.sys.entity.FrameUser;
import com.baseframe.sys.entity.FrameVisitLog;
import com.baseframe.sys.service.IFrameVisitLogService;

/**
 * 系统日志，切面处理类
 *
 */
@Aspect
@Component
public class VisitLogAspect extends AbstractController{
	@Autowired
	private IFrameVisitLogService frameVisitLogService;
	
	@Pointcut("@annotation(com.baseframe.common.annotation.VisitLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		//保存日志
		saveVisitLog(point, time);

		return result;
	}

	private void saveVisitLog(ProceedingJoinPoint joinPoint, long time) {
		System.out.println("===============================visitAspect");
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		FrameVisitLog log = new FrameVisitLog();
		log.setRowguid(UUID.randomUUID().toString().replace("-", ""));
		VisitLog visitlog = method.getAnnotation(VisitLog.class);
		if(visitlog != null){
			//注解上的描述
			log.setModulename(visitlog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
//		log.setMethod(className + "." + methodName + "()");

		//请求的参数
//		Object[] args = joinPoint.getArgs();
//		try{
//			String params = new Gson().toJson(args[0]);
//			sysLog.setParams(params);
//		}catch (Exception e){
//
//		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		log.setVisitip(IPUtils.getIpAddr(request));

		//用户名
//		String username = ((FrameUser) SecurityUtils.getSubject().getPrincipal()).getLoginid();//yong xin de 
//		log.setVisitusername(username);
		//用户名
		
		FrameUser user = getUser();
		if(user != null){
		log.setVisitusername(user.getLoginname());
		log.setVisituserguid(user.getUserguid());
		log.setOuguid(user.getOuguid());
		log.setOuname(user.getOuname());

//		log.setTime(time);
		log.setVisitdate(new Date());
		//保存日志
		frameVisitLogService.insert(log);
		}
	}
}
